package os.kernelProcess.queues;

import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;

import os.MiniThread;

public class ShortestQueue extends MiniQueue
{
	
	private LinkedList<MiniThread> list = new LinkedList<MiniThread>();
	
	@Override
	public void append(MiniThread thread) 
	{
		this.accessQueue.P();
			list.add(thread);
		this.accessQueue.V();
	}

	@Override
	public MiniThread getHead() 
	{
		MiniThread head = null;
		this.accessQueue.P();
			Iterator<MiniThread> iterator = list.iterator();
			head = iterator.next();
			while(iterator.hasNext())
			{
				MiniThread thread = iterator.next();
				if(thread.getRemainingTime() < head.getRemainingTime())
				{
					head = thread;
				}
			}
		this.accessQueue.V();
		return head;
	}

	@Override
	public int getSize() 
	{
		int size = 0;
		this.accessQueue.P();
			size = list.size();
		this.accessQueue.V();
		return size;
	}

	@Override
	public MiniThread removeThread(String tid) 
	{
		MiniThread removed = null;
		this.accessQueue.P();
			Iterator<MiniThread> iterator = list.iterator();
			while(iterator.hasNext())
			{
				removed = iterator.next();
				if(removed.getTid().equals(tid))
				{
					break;
				}
			}
			list.remove(removed);
		this.accessQueue.V();
		return removed;
	}
	
	private class ThreadComparator implements Comparator<MiniThread>
	{
		@Override
		public int compare(MiniThread o1, MiniThread o2) 
		{
			return (o1.getPriority() - o2.getPriority());
		}
	}
}
